<template>
  <div class="container">
    <h2 class="text-center mt-5">申请店铺</h2>
    <form  class="mt-4">
      <div class="form-group">
        <label for="shopName">店铺名称</label>
        <input type="text" id="shopName" v-model="storeInfo.storeName" :class="{ 'is-invalid': shopNameError }" required />
        <div v-if="shopNameError" class="invalid-feedback">店铺名称不能为空</div>
      </div>
      <div class="form-group">
        <label for="contactPhone">联系电话</label>
        <input type="tel" id="contactPhone" v-model="storeInfo.phone" :class="{ 'is-invalid': contactPhoneError }" required />
        <div v-if="contactPhoneError" class="invalid-feedback">联系电话不能为空</div>
      </div>
      <div class="form-group">
        <label for="startTime">开始时间</label>
        <el-time-picker
          id="startTime"
          v-model="storeInfo.storeStartTime"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          placeholder="选择开始时间"
          :class="{ 'is-invalid': startTimeError }"
          required
        />
        <div v-if="startTimeError" class="invalid-feedback">开始时间不能为空</div>
      </div>
      <div class="form-group">
        <label for="endTime">结束时间</label>
        <el-time-picker
          id="endTime"
          v-model="storeInfo.storeEndTime"
          format="HH:mm:ss"
          value-format="HH:mm:ss"
          placeholder="选择结束时间"
          :class="{ 'is-invalid': endTimeError }"
          required
        />
        <div v-if="endTimeError" class="invalid-feedback">结束时间不能为空</div>
      </div>
      <div class="form-group">
        <label for="storeIntro">店铺介绍</label>
        <textarea id="storeIntro" v-model="storeInfo.storeIntro" :class="{ 'is-invalid': storeIntroError }" required></textarea>
        <div v-if="storeIntroError" class="invalid-feedback">店铺介绍不能为空</div>
      </div>
      <div class="permit-info mt-4">
        <h3>店铺许可信息</h3>
        <div class="form-group">
          <label for="businessLicense">营业执照</label>
          <input type="file" id="businessLicense" @change="handleFileChange('businessLicense')" />
        </div>
        <div class="form-group">
          <label for="healthPermit">卫生许可</label>
          <input type="file" id="healthPermit" @change="handleFileChange('healthPermit')" />
        </div>
        <!-- <div class="form-group text-center">
          <button @click="uploadFiles" class="btn btn-success">上传文件</button>
        </div> -->
        <div class="form-group text-center">
          <button type="submit"  @click.prevent="handleSubmit" class="btn btn-primary">提交申请</button>
          <button type="button" @click="resetForm" class="btn btn-secondary ml-3">重置</button>
        </div>
      </div>
    </form>
  </div>
</template>

<script>
import axios from 'axios';
import { ElMessage, ElTimePicker } from 'element-plus';

export default {
  components: {
    ElTimePicker
  },
  data() {
    return {
      storeInfo: {
      },
      files: {
        businessLicense: null,
        healthPermit: null
      },
      filePath:{
        license:"",
        permit:""
      },
      shopNameError: false,
      contactPhoneError: false,
      startTimeError: false,
      endTimeError: false,
      storeIntroError: false
    };
  },
  methods: {

    handleSubmit() {
      this.shopNameError = !this.storeInfo.storeName.trim();
      this.contactPhoneError = !this.storeInfo.phone.trim();
      this.startTimeError = !this.storeInfo.storeStartTime;
      this.endTimeError = !this.storeInfo.storeEndTime;
      this.storeIntroError = !this.storeInfo.storeIntro.trim();
      if (this.storeInfo.storeStartTime && this.storeInfo.storeEndTime) {
      const startTime = new Date(`1970-01-01T${this.storeInfo.storeStartTime}`);
      const endTime = new Date(`1970-01-01T${this.storeInfo.storeEndTime}`);
      if (endTime <= startTime) {
        ElMessage.error('结束时间不能早于或等于开始时间');
        return;
      }
    }
      // if (!this.hasErrors) {
      //   // Handle form submission logic here
      //   console.log('Form submitted:', this.storeInfo);
      // }
     
   
      // 文件上传成功后，再提交表单
      this.uploadFiles();
      this.storeInfo.permit = JSON.stringify(sessionStorage.getItem('permit'));
      this.storeInfo.license = JSON.stringify(sessionStorage.getItem('license'));
      console.log(this.storeInfo)
      axios.post('/meals/store/applyForStore', this.storeInfo)
        .then(response => {
          if (response.data.code === 200) {
            ElMessage.success(response.data.msg);
            this.resetForm();
            this.$router.push('/');
          } else {
            ElMessage.error(response.data.msg);
          }
        })
        .catch(error => {
          ElMessage.error('申请提交失败，请重试！');
          console.error(error);
        });
    },
    handleFileChange(type) {
      const file = event.target.files[0];
      if (file) {
        this.files[type] = file;
      }
    },
    uploadFiles() {
      const formData = new FormData();
      if (this.files.businessLicense) {
        formData.append('license', this.files.businessLicense);
      }
      if (this.files.healthPermit) {
        formData.append('permit', this.files.healthPermit);
      }
        axios.post('/meals/store/upLoad', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        .then(response => {
          if (response.data.code === 200) {
            sessionStorage.setItem('license', response.data.data.license);
            sessionStorage.setItem('permit', response.data.data.permit);
            ElMessage.success(response.data.msg);
            return true;
          } else {
            ElMessage.error(response.data.msg);
            return false;
          }
        })
        .catch(error => {
          ElMessage.error('文件上传失败，请重试！');
          console.error(error);
          return false;
        });
    },
    resetForm() {
      this.storeInfo.storeName = '';
      this.storeInfo.phone = '';
      this.storeInfo.storeStartTime = '';
      this.storeInfo.storeEndTime = '';
      this.storeInfo.storeIntro = '';
      this.files.businessLicense = null;
      this.files.healthPermit = null;
      this.shopNameError = false;
      this.contactPhoneError = false;
      this.startTimeError = false;
      this.endTimeError = false;
      this.storeIntroError = false;
    }
  },
  computed: {
    hasErrors() {
      return this.shopNameError || this.contactPhoneError || this.startTimeError || this.endTimeError || this.storeIntroError;
    }
  }
};
</script>

<style scoped>
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h2 {
  color: #333;
}

.form-group {
  margin-bottom: 1.5rem;
}

label {
  display: block;
  margin-bottom: 0.5rem;
  font-weight: bold;
  color: #555;
}

input[type="text"],
input[type="password"],
input[type="tel"],
input[type="file"] {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  line-height: 1.5;
  color: #495057;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

input[type="text"]:focus,
input[type="password"]:focus,
input[type="tel"]:focus,
input[type="file"]:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

textarea {
  width: 100%;
  padding: 0.5rem;
  font-size: 1rem;
  line-height: 1.5;
  color: #495057;
  background-color: #fff;
  background-clip: padding-box;
  border: 1px solid #ced4da;
  border-radius: 0.25rem;
  transition: border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  resize: vertical; /* 允许垂直调整大小 */
}

textarea:focus {
  border-color: #80bdff;
  outline: 0;
  box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25);
}

.is-invalid {
  border-color: #dc3545;
}

.invalid-feedback {
  display: block;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 80%;
  color: #dc3545;
}

.btn {
  padding: 0.5rem 1rem;
  font-size: 1rem;
  line-height: 1.5;
  border-radius: 0.25rem;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
}

.btn-primary {
  color: #fff;
  background-color: #007bff;
  border-color: #007bff;
}

.btn-primary:hover {
  color: #fff;
  background-color: #0069d9;
  border-color: #0062cc;
}

.btn-secondary {
  color: #fff;
  background-color: #6c757d;
  border-color: #6c757d;
}

.btn-secondary:hover {
  color: #fff;
  background-color: #545b62;
  border-color: #4e555b;
}

.btn-success {
  color: #fff;
  background-color: #28a745;
  border-color: #28a745;
}

.btn-success:hover {
  color: #fff;
  background-color: #218838;
  border-color: #1e7e34;
}

.text-center {
  text-align: center;
}

.mt-5 {
  margin-top: 3rem;
}

.mt-4 {
  margin-top: 1.5rem;
}

.ml-3 {
  margin-left: 1rem;
}
</style>
